package com.dobbinsoft.fw.core.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author:chengchangjiang
 * @Description:
 * @Date:Created in 14:51 2022-09-03
 */
public class AESCBCUtil {
    /**
     * @param content 密文
     * @param key     aes密钥
     * @return 原文
     */

    public static String RealDecrypt(String content, String key) throws Exception {

        //反序列化AES密钥

        SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key.getBytes()), "AES");

        //128bit全零的IV向量

        byte[] iv = new byte[16];

        for (int i = 0; i < iv.length; i++) {

            iv[i] = 0;

        }

        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        //初始化加密器并加密

        Cipher deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        deCipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

        byte[] encryptedBytes = Base64.decodeBase64(content.getBytes());

        byte[] bytes = deCipher.doFinal(encryptedBytes);

        return new String(bytes);

    }
}
